package org.jeecg.modules.flowable.config;

import org.flowable.common.engine.api.delegate.event.FlowableEngineEventType;
import org.flowable.common.engine.api.delegate.event.FlowableEventDispatcher;
import org.flowable.spring.SpringProcessEngineConfiguration;
import org.jeecg.modules.flowable.listener.ProcessCompletedListener;
import org.jeecg.modules.flowable.listener.ProcessStartedListener;
import org.jeecg.modules.flowable.listener.TaskBeforeListener;
import org.jeecg.modules.flowable.listener.TaskCompletedListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.lang.NonNull;

/**
 * flowable 全局监听器配置类
 * flowable监听级别参照 {@link FlowableEngineEventType} org.flowable.common.engine.api.delegate.event
 */
@Configuration
public class FlowListenerConfig implements ApplicationListener<ContextRefreshedEvent> {

    /**
     * 任务节点前置监听
     */
    final TaskBeforeListener taskBeforeListener;
    final TaskCompletedListener taskCompletedListener;
    final ProcessStartedListener processStartedListener;
    final ProcessCompletedListener processCompletedListener;
    final SpringProcessEngineConfiguration engineConfiguration;


    @Autowired
    public FlowListenerConfig(
            TaskBeforeListener taskBeforeListener,
            TaskCompletedListener taskCompletedListener,
            ProcessStartedListener processStartedListener,
            ProcessCompletedListener processCompletedListener,
            SpringProcessEngineConfiguration engineConfiguration) {
        this.taskBeforeListener = taskBeforeListener;
        this.taskCompletedListener = taskCompletedListener;
        this.processStartedListener = processStartedListener;
        this.processCompletedListener = processCompletedListener;
        this.engineConfiguration = engineConfiguration;
    }

    @Override
    public void onApplicationEvent(@NonNull ContextRefreshedEvent event) {
        FlowableEventDispatcher dispatcher = engineConfiguration.getEventDispatcher();
        // 任务创建
        dispatcher.addEventListener(taskBeforeListener, FlowableEngineEventType.TASK_CREATED);
        // 任务完成
        dispatcher.addEventListener(taskCompletedListener, FlowableEngineEventType.TASK_COMPLETED);
        // 流程开始
        dispatcher.addEventListener(processStartedListener, FlowableEngineEventType.PROCESS_STARTED);
        // 流程完成
        dispatcher.addEventListener(processCompletedListener, FlowableEngineEventType.PROCESS_COMPLETED);
    }
}
